package com.moli.iov.notify.util;

import com.moli.iov.notify.model.dto.MailDto;
import com.moli.iov.util.StringUtil;
import java.util.Date;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

/**
 * <p>
 * 邮件工具类
 * </p>
 *
 * @author zql
 * @since 2019/9/10 14:48
 */
@Slf4j
@Component
public class MailUtil {

  /**
   * 注入邮件工具类
   */
  @Autowired
  private JavaMailSenderImpl mailSender;

  /**
   * 发送邮件
   * @param mailDto
   * @return
   */
  public boolean sendMail(MailDto mailDto) {
    try {
      //true表示支持复杂类型
      MimeMessageHelper messageHelper = new MimeMessageHelper(mailSender.createMimeMessage(), true);
      //邮件发信人
      if(StringUtil.isNotBlank(mailDto.getFrom())){
        messageHelper.setFrom(mailDto.getFrom());
      }else{ //邮件发信人从配置项读取
        messageHelper.setFrom(getMailSendFrom());
      }
      //邮件收信人
      messageHelper.setTo(mailDto.getTo().split(","));
      //邮件主题
      messageHelper.setSubject(mailDto.getSubject());
      //邮件内容
      messageHelper.setText(mailDto.getText(), true);

      messageHelper.setSentDate(new Date());

      log.info("正在发送邮件...");
      mailSender.send(messageHelper.getMimeMessage());
      log.info("发送邮件成功：{}->{}", mailDto.getFrom(), mailDto.getTo());
      return true;
    } catch (Exception e) {
      log.error("发送异常", e);
      return false;
    }
  }

  /**
   * 获取邮件发信人
   * @return
   */
  public String getMailSendFrom() {
    return mailSender.getJavaMailProperties().getProperty("from");
  }
}
